<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="rolesList" style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="{row}">
            <el-row :class="['bdbottom',index==0?'bdtop ':'','vcenter']" :gutter="10"
              v-for="(item1,index) in row.children" :key="item1.id">
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag closable @close="removeRight(row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <el-row :gutter="10" :class="[index == 0 ? '':'bdtop','vcenter']"
                  v-for="(item2,index) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRight(row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" @close="removeRight(row,item3.id)" v-for="(item3) in item2.children"
                      :key="item3.id" closable>
                      {{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="width">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="width">
        </el-table-column>
        <el-table-column label="操作" width="width">
          <template slot-scope="{row}">
            <el-button type="primary" @click="editRoles(row)" size="small" icon="el-icon-edit">修改</el-button>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delRoles(row.id)">

              <el-button type="danger" style="margin:0 12px" title="删除" slot="reference" size="mini"
                icon="el-icon-delete">删除
              </el-button>
            </el-popconfirm>
            <el-button type="warning" size="small" @click="showSetRight(row)" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色的弹出框 -->
      <el-dialog title="添加角色信息" :visible.sync="dialogVisibleAdd" width="50%" @close="resetFieldsAdd">
        <el-form ref="addForm" :rules="addRules" :model="rolesListAdd" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesListAdd.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesListAdd.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleAdd = false">取 消</el-button>
          <el-button type="primary" @click="submitFormAdd">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改角色的弹出框 -->
      <el-dialog title="修改角色信息" :visible.sync="dialogVisibleEdit" width="50%" @close="resetFieldsEdit">
        <el-form ref="editForm" :rules="addRules" :model="rolesListEdit" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesListEdit.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesListEdit.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleEdit = false">取 消</el-button>
          <el-button type="primary" @click="submitFormEdit">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限管理的弹出框 -->
      <el-dialog title="分配权限管理" :visible.sync="dialogVisibleSet" width="50%">
        <el-tree show-checkbox :data="rightsList" :props="defaultProps" node-key="id" default-expand-all
          :default-checked-keys="defKeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleSet = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  export default {
    name: "Roles",
    data() {
      return {
        //角色数据列表
        rolesList: [],
        //新增的角色信息
        rolesListAdd: {
          roleName: "",
          roleDesc: ""
        },
        //添加角色的框子隐藏与显示
        dialogVisibleAdd: false,
        //修改角色的框子隐藏与显示
        dialogVisibleEdit: false,
        //分配权限管理的框子的隐藏与显示
        dialogVisibleSet: false,
        //修改角色的信息
        rolesListEdit: {},
        //权限的数据
        rightsList: [],
        //当前被分配权限的用户Id
        roleId: "",
        //树形组件需要的数据
        defaultProps: {
          children: 'children',
          label: 'authName'
        },
        //默认勾选的节点Id值
        defKeys: [],
        // 校验规则
        addRules: {
          roleName: [{
            required: true,
            message: '不能为空哦~',
            trigger: 'blur'
          }, ],
          roleDesc: [{
            required: true,
            message: '不能为空哦~',
            trigger: 'blur'
          }, ],
        }
      }
    },
    methods: {
      //获取角色列表信息
      async getRolesList() {
        let result = await this.$requests.get("roles")
        if (result.meta.status == 200) {
          this.rolesList = result.data
        }
      },
      //添加角色的按钮回调
      addRoles() {
        this.dialogVisibleAdd = true
      },
      //添加角色表单验证和发送请求
      submitFormAdd() {
        this.$refs.addForm.validate(async (valid) => {
          if (valid) {
            this.dialogVisibleAdd = false
            let result = await this.$requests.post("roles", this.rolesListAdd)
            if (result.meta.status == 201) {
              this.$message({
                message: "添加角色成功",
                type: "success"
              })
              this.getRolesList()
            } else {
              this.$message("添加角色失败")
            }
          } else {
            this.$message("请认真填写哦")
            return false;
          }
        });
      },
      //清空添加角色表单
      resetFieldsAdd() {
        this.$refs.addForm.resetFields()
      },
      //修改按钮的回调
      editRoles(row) {
        this.dialogVisibleEdit = true
        this.rolesListEdit = JSON.parse(JSON.stringify(row))
      },
      //修改信息表单验证和发送请求
      submitFormEdit() {
        this.$refs.editForm.validate(async (valid) => {
          if (valid) {
            this.dialogVisibleEdit = false
            let result = await this.$requests.put(`roles/${this.rolesListEdit.id}`, {
              roleName: this.rolesListEdit.roleName,
              roleDesc: this.rolesListEdit.roleDesc
            })
            if (result.meta.status == 200) {
              this.$message({
                message: "修改角色成功",
                type: "success"
              })
              this.getRolesList()
            } else {
              this.$message("修改角色失败")
            }
          } else {
            this.$message("请认真填写哦")
            return false;
          }
        });
      },
      //清空修改角色表单
      resetFieldsEdit() {
        this.$refs.editForm.resetFields()
      },
      //删除角色按钮的回调
      async delRoles(id) {
        let result = await this.$requests.delete(`roles/${id}`)
        if (result.meta.status == 200) {
          this.$message({
            message: '删除信息成功',
            type: 'success'
          });
          this.getRolesList()
        } else {
          this.$message(`${result.meta.msg}`);
        }
      },
      //删除tag小标签的回调
      async removeRight(row, rightId) {
        //提示用户
        let result = await this.$confirm('将永久删除该信息哦~, 是否继续呀?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error);
        if (result == "confirm") {
          let result2 = await this.$requests.delete(`roles/${row.id}/rights/${rightId}`)
          if (result2.meta.status == 200) {
            this.$message({
              message: "删除成功",
              type: "success"
            })
            //局部赋值,不影响全局
            row.children = result2.data
          } else {
            this.$message("删除失败了")
          }
        } else {
          return this.$message("取消删除")
        }
      },
      //权限管理按钮的回调
      async showSetRight(row) {
        this.roleId = row.id
        let result = await this.$requests.get("rights/tree")
        if (result.meta.status == 200) {
          this.rightsList = result.data
        } else {
          this.$message("获取信息失败")
        }
        this.defKeys = [] //先置空
        this.getLeafKeys(row, this.defKeys)
        this.dialogVisibleSet = true
      },
      //通过递归形式获取角色三级Id
      getLeafKeys(node, arr) {
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach((item) => {
          this.getLeafKeys(item, arr)
        })
      },
      //分配权限确认按钮的回调
      async allotRights() {
        this.dialogVisibleSet = false
        const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
        const idStr = keys.join(",")
        let result = await this.$requests.post(`roles/${this.roleId}/rights`, {
          rids: idStr
        })
        if (result.meta.status == 200) {
          this.$message({
            message: "分配权限成功",
            type: "success"
          })
          this.getRolesList()
        } else {
          return this.$message("分配权限失败")
        }
      }
    },
    mounted() {
      this.getRolesList()
    }
  }

</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #eee;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }

</style>
